<template>
  <base-layout
    :dialogVisible="dialogVisible"
    :dialogTitle="dialogTitle"
    @dialog-close="dialogClose"
    :visibleContent2="true"
    :visibleContent3="true"
  >
    <template #searchPanel>
      <el-form
        :inline="true"
        ref="fromdata1"
        :model="fromdata"
        :rules="rules"
        label-width="130px"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">采购基础信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购编号:">
              <el-input clearable readonly="readonly" v-model="fromdata.code" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购门店:" prop="storeId">
              <Job-shop
                v-model="fromdata.storeId"
                placeholder="采购门店"
                :defaultStoreId="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购供应商:" prop="purchaseSupplierId">
              <el-select
                clearable
                filterable
                style="width: 200px"
                v-model="fromdata.purchaseSupplierId"
                placeholder="采购供应商"
              >
                <el-option
                  v-for="item in supplierList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.supplierName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购类型:" prop="type">
              <el-select clearable style="width: 200px" v-model="fromdata.type">
                <el-option
                  v-for="item in dict['采购类型']"
                  :key="item.index"
                  :value="item.value"
                  :label="item.text"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="单据日期:" prop="receiptsTime">
              <el-date-picker
                value-format="yyyy-MM-dd hh:mm:ss"
                v-model="fromdata.receiptsTime"
                type="datetime"
                disabled="disabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商联系人:">
              <el-input clearable v-model="fromdata.supplierUserName" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商联系方式:">
              <el-input clearable v-model.number="fromdata.supplierPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库备注:" prop="remark">
              <el-input
                type="textarea"
                :rows="6"
                placeholder=""
                v-model="fromdata.remark"
                style="width: 600px"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <template #contentPanel>
      <el-form
        :inline="true"
        ref="fromdata2"
        :model="fromdata"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">采购人员</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购人员:" prop="userName">
              <el-input clearable v-model="fromdata.userName" @focus="employeeFocus" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式:" prop="phone">
              <el-input clearable v-model="fromdata.phone" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <template #contentPanel2>
      <el-form
        :inline="true"
        ref="fromdata"
        :model="fromdata"
        :rules="rules"
        label-width="90px"
        label-position="right"
        class="insuranceForm"
      >
        <el-row>
          <el-col :span="22">采购配件列表</el-col>
          <el-col :span="2">
            <el-button icon="el-icon-plus" type="primary" @click="addInventory"
              >添加采购配件</el-button
            >
          </el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <data-table
            :value="fromdata.partsList"
            :total-count="fromdata.partsList.length"
            :has-action="true"
            :table-column-attributes="tableColumnAttributes"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :width="160"
            :localPage="true"
          >
            <template #action="{ row }">
              <i
                class="el-icon-delete"
                title="删除"
                style="color: red; margin-left: 20px; cursor: pointer"
                @click="deleteLochost(row)"
              ></i>
            </template>
            <template #allNum>
              <el-col :span="8" v-if="allMount">
                <span style="line-height: 10px; text-align: left; color: #606266"
                  >采购配件总金额：<span style="color: #f40; font-size: 20px"
                    >￥{{ allMount }}</span
                  ></span
                >
              </el-col>
              <el-col :span="8" v-if="freePriceAll">
                <span style="line-height: 10px; text-align: left; color: #606266"
                  >采购配件总优惠金额：<span style="color: #f40; font-size: 20px"
                    >￥{{ freePriceAll }}</span
                  ></span
                >
              </el-col>
              <el-col :span="8" v-if="allMount1">
                <span style="line-height: 10px; text-align: left; color: #606266"
                  >配件总数：<span style="color: #f40; font-size: 20px">{{
                    allMount1
                  }}</span></span
                >
              </el-col>
            </template>
          </data-table>
        </el-row>
      </el-form>
    </template>
    <template #contentPanel3>
      <el-row>
        <el-col :span="24" align="right" justify="center">
          <el-col :span="24">
            <span style="line-height: 10px; text-align: left; color: #606266"
              >采购总金额：<span style="color: #f40; font-size: 20px" v-if="allMount"
                >￥{{ allMount }}</span
              ></span
            >
          </el-col>
          <el-col :span="24" style="margin-top: 20px">
            <el-button type="success" @click="saveUpdate">保存采购单</el-button>
          </el-col>
        </el-col>
      </el-row>
    </template>
    <template #dialog>
      <SelectAccessories
        :storageId="fromdata.storeId"
        v-if="showSelect"
        :supplierId="fromdata.purchaseSupplierId"
        @partsList="partsList"
      />
      <EmployeeTable
        v-if="showEmployeeTable"
        @roleIdListSelectCheck="employeListSelectCheck"
        :formData="userFrom"
        :checkList="[fromdata.manageUserName]"
      />
    </template>
  </base-layout>
</template>
<script>
import baseMixin from "@/mixins/base";
import { getSupplierByStorId } from "@/api/after-sale/systemManage/supplier";
import {
  add,
  getFindById,
  update,
  getPurchaseCode,
} from "@/api/after-sale/purchaseManage/purchaseRecords";
import EmployeeTable from "../../systemManage/store/components/EmployeeTable";
import SelectAccessories from "@/components/SelectAccessories/index"; //导入组件
import { getDict, parseTimeToYMDHMS } from "@/utils";
import store from "@/store";
export default {
  components: {
    EmployeeTable,
    SelectAccessories,
  },
  mixins: [
    baseMixin({
      addData: add,
      updateData: update,
      format(res) {
        return res.map((data) => {
          if (!data.freePrice) {
            data.freePrice = 0;
          }
          return data;
        });
      },
    }),
  ],
  watch: {
    "fromdata.partsList": {
      handler(value) {
        this.sumAllMount();
      },
      deep: true,
    },
    "fromdata.purchaseSupplierId": function (value) {
      if (value) {
        this.supplierList.forEach((e) => {
          if (e.id === value) {
            this.fromdata.supplierUserName = e.contactName;
            this.fromdata.supplierPhone = e.contactPhone;
          }
        });
      }
    },
    "fromdata.storeId": function (value) {
      this.cleansupplier();
      if (value) {
        this.getSupplierByStorId(value, "配件供应商");
      } else {
        this.getSupplierByStorId(store.state.user.entryStore, "配件供应商");
      }
    },
  },
  data() {
    return {
      fromdata: {
        storeId: null,
        partsList: [],
        userName: "",
        phone: "",
        receiptsTime: parseTimeToYMDHMS(new Date()),
      },
      rules: {
        storeId: [{ required: true, message: "请选择采购门店", trigger: "change" }],
        purchaseSupplierId: [
          { required: true, message: "请选择采购供应商", trigger: "bulr" },
        ],
        type: [{ required: true, message: "请选择采购类型", trigger: "change" }],
        receiptsTime: [{ required: true, message: "请选择单据日期", trigger: "change" }],
        supplierUserName: [
          { required: true, message: "请输入供应商联系人", trigger: "bulr" },
        ],
        supplierPhone: [
          { required: true, message: "请输入供应商联系方式", trigger: "bulr" },
        ],
        userName: [{ required: true, message: "请选择采购人员", trigger: ["change"] }],
      },
      userFrom: {},
      allMount: null,
      allMount1: null,
      freePriceAll: null,
      dict: [],
      showSelect: false, // 是否展示配件组件
      showEmployeeTable: false, //  是否展示员工组件
      supplierList: [],
      tableColumnAttributes: [
        { name: "配件编号", value: "partsCode", type: "text" },
        { name: "配件名称", value: "partsName", type: "text" },
        { name: "配件类别", value: "partsType", type: "text" },
        { name: "配件单位", value: "partsUnit", type: "text" },
        {
          name: "采购数量",
          value: "purchaseNum",
          type: "inputNumber",
          action: function (row) {
            row.amount = (row.purchasePrice * row.purchaseNum - row.freePrice).toFixed(2);
          },
        },
        {
          name: "采购成本",
          value: "purchasePrice",
          type: "input",
          action: function (row) {
            row.amount = (row.purchasePrice * row.purchaseNum - row.freePrice).toFixed(2);
          },
        },
        {
          name: "优惠金额",
          value: "freePrice",
          type: "inputNumber",
          action: function (row) {
            row.amount = (row.purchasePrice * row.purchaseNum - row.freePrice).toFixed(2);
          },
        },
        { name: "总金额", value: "amount", type: "text" },
      ],
    };
  },
  methods: {
    // 清空供应商表单数据
    cleansupplier() {
      this.$set(this.fromdata, "purchaseSupplierId", "");
      this.fromdata.supplierUserName = null;
      this.fromdata.supplierPhone = null;
    },
    // 动态计算表格总和
    sumAllMount() {
      this.allMount = null;
      this.allMount1 = null;
      this.freePriceAll = null;
      this.fromdata.partsList.forEach((e) => {
        if (e.amount) {
          this.allMount += Number.parseFloat(e.amount)
        }
        if (e.purchaseNum) {
          this.allMount1 += Number.parseInt(e.purchaseNum)
        }
        if (e.freePrice) {
          this.freePriceAll += Number.parseInt(e.freePrice)
        }
      });
      this.allMount = this.allMount.toFixed(2)
    },
    //删除临时配件
    deleteLochost(row) {
      this.fromdata.partsList = this.fromdata.partsList.filter((e) => e.id != row.id);
    },
    // 打开配件选择
    addInventory() {
      this.showSelect = true;
      this.showEmployeeTable = false;
      this.handleDataInsert("配件选择");
    },
    //打开员工选择列表
    employeeFocus() {
      this.showSelect = false;
      this.showEmployeeTable = true;
      this.userFrom.storeId = this.fromdata.storeId;
      console.log(this.userFrom);
      this.handleDataInsert("管理人员列表");
    },
    //员工选择
    employeListSelectCheck(select) {
      this.$refs["fromdata2"].clearValidate("userName");
      this.fromdata.userName = select[0].userName;
      this.fromdata.phone = select[0].phone;
      this.fromdata.userId = select[0].id;
      this.dialogClose();
    },
    saveUpdate() {
      this.$refs["fromdata1"].validate((valid) => {
        this.$refs["fromdata2"].validate((valid1) => {
          if (valid && valid1) {
            this.handleDataUpdate(this.fromdata);
            this.closeRouter();
          }
        });
      });
    },
    async detail(id) {
      let { data } = await getFindById(id);
      this.fromdata = data;
    },
    async getPurchaseCode() {
      let { data } = await getPurchaseCode();
      this.fromdata.code = data;
    },
    // 获取供应商
    async getSupplierByStorId(storeId, supplierType) {
      let { data } = await getSupplierByStorId(storeId, supplierType);
      this.supplierList = data;
    },
    // 选择配件
    partsList(value) {
      if (value.length > 0) {
        value.forEach((e) => {
          let index = true;
          this.fromdata.partsList.forEach((g) => {
            if (e.id === g.id) {
              index = false;
            }
          });
          if (index) {
            let { ...data } = {
              ...e,
              partsUnit: e.unit,
              partsId: e.id,
              partsType: e.partsDictValue,
              freePrice: null,
            };
            this.fromdata.partsList.push(data);
          }
        });
      }
      this.dialogClose();
    },
  },
  mounted() {
    this.dict = getDict(["采购类型"]);
    this.getSupplierByStorId(store.state.user.entryStore, "配件供应商");
    let id = this.$route.query.id;
    if (id) {
      this.fromdata.id = id;
      this.detail(id);
    } else {
      this.getPurchaseCode();
    }
  },
};
</script>
<style lang="scss" scoped></style>
